package com.vlin.filter.session;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.session.Session;
import org.springframework.session.SessionRepository;
import org.springframework.web.filter.OncePerRequestFilter;

@WebFilter(displayName="sessionFilter", urlPatterns = SessionFilter.URL_PATTERN, 
	initParams = {@WebInitParam(name=SessionFilter.INIT_PARAM,value=SessionFilter.EXCLUDE_PAGES)})
public class SessionFilter extends OncePerRequestFilter {

	private static final Logger logger = LoggerFactory.getLogger(SessionFilter.class);
	
	public static final String URL_PATTERN = "/*";
	
	public static final String INIT_PARAM = "EXCLUDED_PAGES";
	
	public static final String EXCLUDE_PAGES = "";
	
	private List<String> filtList;
	
	@Autowired
	private SessionRepository sessionRepository;
	
	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		String token = request.getHeader("token");
		Session session = sessionRepository.findById(token);
		if(session == null) {
			
		}
	}

	@Override
	protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
		if(filtList == null ) {
			filtList = new ArrayList<String>();
			String exclude = getFilterConfig().getInitParameter(INIT_PARAM);
			if(exclude != null) {
				String[] values = exclude.split(";");
				for(String value : values) {
					filtList.add(value);
				}
			}
		}
		
		String uri = request.getRequestURI();
		logger.info("Uri : {}", uri);
		for(String list : filtList) {
			if(list.equals(uri)) {
				return true;
			}
		}
		return false;
	}
	
	

	

}
